package com.liushuo.dao;

import com.liushuo.entity.Mistake;
import com.liushuo.util.DBUtil;

import java.sql.*;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

public class MistakeDao {

    public boolean recordMistake(String userId, int questionId, int wrongAnswer){
        try {
            Connection conn = DBUtil.getConnection();
            String sql = "INSERT INTO mistakes (user_id, question_id, date, wrong_answer) VALUES (?, ?, ?, ?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, userId);
            ps.setInt(2, questionId);

            Timestamp nowTime = new Timestamp(System.currentTimeMillis());
            ps.setTimestamp(3, nowTime);
            ps.setInt(4, wrongAnswer);
            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public List<Mistake> getMistakes(String userId, Date startDate, Date endDate) {
        List<Mistake> mistakes = new ArrayList<>();
        try {
            Connection conn = DBUtil.getConnection();
            String sql = "SELECT * FROM mistakes WHERE user_id = ? AND date BETWEEN ? AND ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, userId);
            ps.setTimestamp(2, DBUtil.toStartOfDay((java.sql.Date)startDate));
            ps.setTimestamp(3, DBUtil.toEndOfDay((java.sql.Date)endDate));
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Mistake mistake = Mistake.builder()
                        .userId(rs.getString("user_id"))
                        .questionId(rs.getInt("question_id"))
                        .date(rs.getTimestamp("date"))
                        .wrongAnswer(rs.getInt("wrong_answer"))
                        .build();
                mistakes.add(mistake);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return mistakes;
    }

}
